package org.secur.eave.util

import android.annotation.SuppressLint
import com.github.shadowsocks.bg.BaseService
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import org.secur.eave.api.ApiService
import org.secur.eave.dao.StealthResponse
import org.secur.eave.dao.StealthServer
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import android.util.Base64
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Handler
import android.os.Looper
import java.net.NetworkInterface
import java.util.Collections

@Suppress("NAME_SHADOWING")
class BaseUtil {
    companion object{
        
        
        
        fun decodeStealthServer(encodedString: String, onSuccess: (ip: String) -> Unit, onFailure: (error: String) -> Unit) {
            try {
                val trimmedString = encodedString.removePrefix("ss://")
                
                val parts = trimmedString.split("@")
                if (parts.size != 2) {
                    onFailure("Invalid encoded string format")
                    return
                }
                val base64Part = parts[0]
                val addressPart = parts[1]
                
                val decodedBytes = Base64.decode(base64Part, Base64.NO_WRAP)
                val decodedString = String(decodedBytes, Charsets.UTF_8)
                
                val methodAndPwd = decodedString.split(":")
                if (methodAndPwd.size != 2) {
                    onFailure("Invalid method and password format")
                    return
                }
                val stealthMethod = methodAndPwd[0]
                val stealthPwd = methodAndPwd[1]
                
                val addressParts = addressPart.split(":")
                if (addressParts.size != 2) {
                    onFailure("Invalid IP and port format")
                    return
                }
                val ip = addressParts[0]
                val port = addressParts[1]
                
                // 成功解析，调用成功回调
                onSuccess(ip)
                
            } catch (e: Exception) {
                // 捕获异常并调用失败回调
                onFailure(e.message ?: "Unknown error")
            }
        }
        

        

        
        
        fun getIPAddress(): String {
            try {
                val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
                for (networkInterface in interfaces) {
                    val addresses = Collections.list(networkInterface.inetAddresses)
                    for (address in addresses) {
                        if (!address.isLoopbackAddress) {
                            val hostAddress = address.hostAddress
                            if (hostAddress != null) {
                                if (hostAddress.indexOf(':') < 0) {
                                    return hostAddress
                                }
                            }
                        }
                    }
                }
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
            return "IP地址不可用"
        }
        
        @SuppressLint("DefaultLocale")
		fun formatDataRate(rate: Long): String {
            return when {
                rate >= 900_000_000 -> String.format("%.1f gb/s", rate / 1_000_000_000.0)
                rate >= 900_000 -> String.format("%.1f mb/s", rate / 1_000_000.0)
                rate >= 900 -> String.format("%.1f kb/s", rate / 1_000.0)
                else -> "$rate b/s"
            }
        }
        
        @SuppressLint("DefaultLocale")
		fun formatDataRateTotal(rate: Long): String {
            return when {
                rate >= 900_000_000 -> String.format("%.1f gb", rate / 1_000_000_000.0)
                rate >= 900_000 -> String.format("%.1f mb", rate / 1_000_000.0)
                rate >= 900 -> String.format("%.1f kb", rate / 1_000.0)
                else -> "$rate b"
            }
        }
        
        
        fun checkVpnConnection(context: Context, callback: (Boolean) -> Unit) {
            val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            
            // 检查当前的网络状态
            val activeNetwork = connectivityManager.activeNetwork
            val activeNetworkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork)
            val isVpnConnected = activeNetworkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
            
            // 使用 Handler 和 Runnable 实现延迟
            Handler(Looper.getMainLooper()).postDelayed({
                callback(isVpnConnected)
            }, 0)
            
            // 注册网络回调以监听未来的网络状态变化
            val networkRequest = NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build()
            
            connectivityManager.registerNetworkCallback(networkRequest, object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
                    val isVpnConnected = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
                    
                    Handler(Looper.getMainLooper()).postDelayed({
                        callback(isVpnConnected)
                    }, 500)
                }
                
                override fun onLost(network: Network) {
                    val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
                    val isVpnConnected = networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
                    
                    Handler(Looper.getMainLooper()).postDelayed({
                        callback(isVpnConnected)
                    }, 500)
                }
            })
        }
        
        
        fun convertStealthServer(server: StealthServer): String {
            // 构建要进行 Base64 编码的字符串
            val baseString = "${server.secureWaveMethod}:${server.secureWavePwd}"
            
            // 将 baseString 进行 Base64 编码
            val base64String = Base64.encodeToString(baseString.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)
            
            // 构建最终的格式字符串
            return "ss://$base64String@${server.secureWaveIp}:${server.secureWavePort}"
        }
        fun fetchStealthLinkResult(
                onSuccess: (List<StealthServer>) -> Unit,
                onFailure: (Throwable) -> Unit
        ) {
            val call = RetrofitClient.instance.getStealthLinkResult()
            call.enqueue(object : Callback<StealthResponse> {
                override fun onResponse(call: Call<StealthResponse>, response: Response<StealthResponse>) {
                    if (response.isSuccessful) {
                        val stealthResponse = response.body()
                        if (stealthResponse != null) {
                            onSuccess(stealthResponse.result)
                        } else {
                            onFailure(Exception("Response body is null"))
                        }
                    } else {
                        onFailure(Exception("Request failed with status code: ${response.code()}"))
                    }
                }
                
                override fun onFailure(call: Call<StealthResponse>, t: Throwable) {
                    onFailure(t)
                }
            })
        }
        
        
        object RetrofitClient {
            private const val BASE_URL = "https://securewave.top/"
            val instance: ApiService by lazy {
                val retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                
                retrofit.create(ApiService::class.java)
            }
        }
        
        
        var stateListener: ((BaseService.State) -> Unit)? = null
        
        fun requestPermission(context: Context){
            XXPermissions.with(context)
                .permission(Permission.POST_NOTIFICATIONS)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (!allGranted) {
                            return
                        }
                    }
                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                        if (doNotAskAgain) {
                            XXPermissions.startPermissionActivity(context, permissions)
                        } else {
                        }
                    }
                })
        }
    }
}